package com.chenchao.reflection;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

/**
 * @encoding : UTF-8
 * @Time : 2020/12/2 19:16
 * @Author : Chen Chao
 * @File : javaSE.com.chenchao.reflection.Test11.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 泛型反射
 */
public class Test11 {
    public static void test01(Map<String,Integer> map, List<String> list){

    }
    public static Map<String,Integer>  test02(){
        return null;
    }
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException {
        Class aClass = Class.forName("com.chenchao.reflection.Test11");
        Method test01 = aClass.getMethod("test01", Map.class, List.class);
        Type[] genericParameterTypes = test01.getGenericParameterTypes();
        for (Type genericParameterType : genericParameterTypes) {
            System.out.println(genericParameterType);
            //java.util.Map<java.lang.String, java.lang.Integer>
            //java.util.List<java.lang.String>

            if(genericParameterType instanceof ParameterizedType){
                /*如果是结构化数据类型*/
                ParameterizedType genericParameterType1 = (ParameterizedType) genericParameterType;
                /*获得真实参数类型*/
                Type[] actualTypeArguments = genericParameterType1.getActualTypeArguments();
                for (Type actualTypeArgument : actualTypeArguments) {
                    System.out.println(actualTypeArgument);
                    //class java.lang.String
                    //class java.lang.Integer
                }
            }
        }

        System.out.println("通过注解获取返回值的泛型");
        Method test02 = aClass.getMethod("test02");
        Type genericReturnType = test02.getGenericReturnType();
        System.out.println(genericReturnType);
        if(genericReturnType instanceof ParameterizedType){
            ParameterizedType genericReturnType1 = (ParameterizedType) genericReturnType;
            Type[] actualTypeArguments = genericReturnType1.getActualTypeArguments();
            for (Type actualTypeArgument : actualTypeArguments) {
                System.out.println(actualTypeArgument);
                //java.util.Map<java.lang.String, java.lang.Integer>
                //class java.lang.String
                //class java.lang.Integer
            }
        }
    }
}
